#!/bin/bash
# ThingsBoard 备份列表查询工具
# 版本: 1.0.1

# 记录当前工作目录
CURRENT_DIR=$(pwd)

# 获取脚本所在目录的绝对路径
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)

# 根据脚本目录计算项目根目录路径
if [[ "$SCRIPT_DIR" == */scripts/tools ]]; then
  # 如果脚本位于scripts/tools目录中
  PROJECT_ROOT=$(cd "$SCRIPT_DIR/../.." && pwd)
elif [[ "$SCRIPT_DIR" == */scripts/* ]]; then
  # 如果脚本位于scripts目录或其他子目录中
  PROJECT_ROOT=$(echo "$SCRIPT_DIR" | sed 's|\(.*\)/scripts.*|\1|')
else
  # 否则假设当前目录是项目根目录
  PROJECT_ROOT=$(pwd)
fi

# 配置文件路径
CONFIG_FILE="$PROJECT_ROOT/config/backup_env.conf"

# 检查配置文件是否存在
if [ ! -f "$CONFIG_FILE" ]; then
  echo "错误: 配置文件不存在: $CONFIG_FILE"
  exit 1
fi

# 导入共用函数 - 使用绝对路径
COMMON_SCRIPT="$PROJECT_ROOT/scripts/common.sh"
if [ -f "$COMMON_SCRIPT" ]; then
  source "$COMMON_SCRIPT"
else
  echo "错误: 共用脚本不存在: $COMMON_SCRIPT"
  exit 1
fi

log_info "===== ThingsBoard 备份列表查询工具 V1.0.1 ====="

# 检查s3cmd是否安装
if ! command -v s3cmd &> /dev/null; then
    log_warn "s3cmd未安装，正在安装..."
    apt-get update && apt-get install -y s3cmd || log_error "s3cmd安装失败"
fi

# 显示帮助
function show_help {
    echo "用法: $0 [选项]"
    echo "选项:"
    echo "  -f       查询全量备份"
    echo "  -d       查询增量备份"
    echo "  -a       查询所有备份"
    echo "  -s       直接列出S3/MinIO存储内容（排查用）"
    echo "  -v       显示详细信息"
    echo "  -h       显示帮助信息"
    exit 0
}

# 设置默认查询类型
QUERY_FULL=false
QUERY_DIFF=false
LIST_S3=false
VERBOSE=false

# 处理命令行参数
while getopts "fdashv" opt; do
    case $opt in
        f) QUERY_FULL=true ;;
        d) QUERY_DIFF=true ;;
        a) QUERY_FULL=true; QUERY_DIFF=true ;;
        s) LIST_S3=true ;;
        v) VERBOSE=true ;;
        h) show_help ;;
        *) show_help ;;
    esac
done

# 如果没有指定选项，默认查询所有
if [ "$QUERY_FULL" = "false" ] && [ "$QUERY_DIFF" = "false" ] && [ "$LIST_S3" = "false" ]; then
    QUERY_FULL=true
    QUERY_DIFF=true
fi

# 显示配置信息
log_info "MinIO配置信息:"
echo "MINIO_HOST: $MINIO_HOST"
echo "MINIO_PORT: $MINIO_PORT"
echo "MINIO_BUCKET: $MINIO_BUCKET"
echo "MINIO_FULL_PREFIX: $MINIO_FULL_PREFIX"
echo "MINIO_DIFF_PREFIX: $MINIO_DIFF_PREFIX"

# 直接列出MinIO存储内容
if [ "$LIST_S3" = "true" ]; then
    log_info "直接列出MinIO存储内容..."

    # 创建临时s3cfg配置文件
    TEMP_S3CFG=$(mktemp)
    cat > "$TEMP_S3CFG" << EOF
[default]
access_key = $MINIO_USER
secret_key = $MINIO_PASSWORD
host_base = $MINIO_HOST:$MINIO_PORT
host_bucket = $MINIO_HOST:$MINIO_PORT
use_https = False
signature_v2 = False
EOF

    echo "存储桶列表:"
    echo "----------------------------------------"
    s3cmd -c "$TEMP_S3CFG" ls
    echo "----------------------------------------"

    echo "存储桶内容: s3://$MINIO_BUCKET/"
    echo "----------------------------------------"
    s3cmd -c "$TEMP_S3CFG" ls "s3://$MINIO_BUCKET/"
    echo "----------------------------------------"

    echo "全量备份目录内容: s3://$MINIO_BUCKET/$MINIO_FULL_PREFIX/"
    echo "----------------------------------------"
    s3cmd -c "$TEMP_S3CFG" ls "s3://$MINIO_BUCKET/$MINIO_FULL_PREFIX/"
    s3cmd -c "$TEMP_S3CFG" ls "s3://$MINIO_BUCKET/$MINIO_FULL_PREFIX/basebackups_005/"
    echo "----------------------------------------"

    echo "增量备份目录内容: s3://$MINIO_BUCKET/$MINIO_DIFF_PREFIX/"
    echo "----------------------------------------"
    s3cmd -c "$TEMP_S3CFG" ls "s3://$MINIO_BUCKET/$MINIO_DIFF_PREFIX/"
    s3cmd -c "$TEMP_S3CFG" ls "s3://$MINIO_BUCKET/$MINIO_DIFF_PREFIX/basebackups_005/"
    echo "----------------------------------------"

    # 清理临时文件
    rm -f "$TEMP_S3CFG"
fi

# 查询全量备份
if [ "$QUERY_FULL" = "true" ]; then
    log_info "查询全量备份列表..."

    # 设置环境变量
    export WALG_S3_PREFIX="s3://${MINIO_BUCKET}/${MINIO_FULL_PREFIX}"
    export AWS_ACCESS_KEY_ID="${MINIO_USER}"
    export AWS_SECRET_ACCESS_KEY="${MINIO_PASSWORD}"
    export AWS_ENDPOINT="http://${MINIO_HOST}:${MINIO_PORT}"
    export AWS_S3_FORCE_PATH_STYLE="true"

    echo "全量备份前缀: ${WALG_S3_PREFIX}"
    echo "----------------------------------------"
    if [ "$VERBOSE" = "true" ]; then
        wal-g backup-list --detail
    else
        wal-g backup-list
    fi
    echo "----------------------------------------"

    # 检查是否存在错误
    if [ $? -ne 0 ]; then
        log_warn "查询全量备份失败，尝试使用其他参数..."
        echo "尝试移除WAL_G前缀中的basebackups_005:"
        export WALG_S3_PREFIX="s3://${MINIO_BUCKET}/${MINIO_FULL_PREFIX}"
        wal-g backup-list
    fi
fi

# 查询增量备份
if [ "$QUERY_DIFF" = "true" ]; then
    log_info "查询增量备份列表..."

    # 设置环境变量
    export WALG_S3_PREFIX="s3://${MINIO_BUCKET}/${MINIO_DIFF_PREFIX}"
    export AWS_ACCESS_KEY_ID="${MINIO_USER}"
    export AWS_SECRET_ACCESS_KEY="${MINIO_PASSWORD}"
    export AWS_ENDPOINT="http://${MINIO_HOST}:${MINIO_PORT}"
    export AWS_S3_FORCE_PATH_STYLE="true"

    echo "增量备份前缀: ${WALG_S3_PREFIX}"
    echo "----------------------------------------"
    if [ "$VERBOSE" = "true" ]; then
        wal-g backup-list --detail
    else
        wal-g backup-list
    fi
    echo "----------------------------------------"

    # 检查是否存在错误
    if [ $? -ne 0 ]; then
        log_warn "查询增量备份失败，尝试使用其他参数..."
        echo "尝试移除WAL_G前缀中的basebackups_005:"
        export WALG_S3_PREFIX="s3://${MINIO_BUCKET}/${MINIO_DIFF_PREFIX}"
        wal-g backup-list
    fi
fi

log_info "查询完成"
exit 0
